package cn.com.guage.transtation.controller;

import cn.com.guage.transtation.service.TccTransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/transfer")
public class TransferController {
    @Autowired
    private TccTransferService transferService;

    @PostMapping("/tcc")
    public String transfer(@RequestParam String txId,
                           @RequestParam Long fromId,
                           @RequestParam Long toId,
                           @RequestParam int amount) {
        try {
            // Try 阶段
            boolean tryResult = transferService.tryTransfer(txId, fromId, toId, amount);
            if (!tryResult) {
                transferService.cancelTransfer(txId, fromId, toId, amount);
                return "余额不足";
            }

            // Confirm 阶段
            transferService.confirmTransfer(txId, fromId, toId, amount);
            return "转账成功";
        } catch (Exception e) {
            // 异常时回滚
            transferService.cancelTransfer(txId, fromId, toId, amount);
            return "转账失败: " + e.getMessage();
        }
    }
}